package com.yh.app.common;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.yh.base.service.BaseService;
import com.yh.base.util.CookieUtil;
import com.yh.base.util.ObjectUtil;
import com.yh.base.util.StringUtil;

/**
 * 
 * <功能简述>
 * 
 * @author  严华
 * @version  [版本号, 2012-11-4]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class SessionConfig {
    private Map<String, Object> dataMap = new HashMap<String, Object>();
    private BaseService baseService;

    private final static Logger logger = Logger.getLogger(SessionConfig.class);
    private final static String SPACE = ""; // 不存在值时的session替换
    private final static String SQL_PREFIX = "com.hhos.app.sys.model.sys.";

    /**
     * 
     * 根据userId和roleId缓存session 信息
     *
     * @author  严华
     * @param userId
     * @param request [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     */
    public void init(String userId, HttpServletRequest request) {
        if (baseService == null) {
            this.initBaseService(request);
        }

        // 初始化员工基本信息
        this.initStaffInfo(userId);

        // 初始化员工的角色权限
        String roleIds = initStaffRole(userId);

        // 初始化菜单/功能权限
        this.initMenuInfoList(userId, roleIds);

        // 初始化数据权限
        this.initPrivilegeInfo(userId, roleIds);


        // 最后将所有信息，写入session
        this.writeDataToSession(request);

    }

    @SuppressWarnings("rawtypes")
    public void destroySession() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        Enumeration sessionKeys = session.getAttributeNames();
        while (sessionKeys.hasMoreElements()) {
            session.setAttribute(ObjectUtil.toString(sessionKeys.nextElement()), null);
        }
        // 存userId到cookie
        CookieUtil cookie = new CookieUtil(request, ServletActionContext.getResponse());
        cookie.deleteCookie("USER_ID");
    }


    @SuppressWarnings("rawtypes")
    private void writeDataToSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        // 将dataMap中的信息写入session
        Iterator it = dataMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            logger.debug("key:" + key);
            logger.debug("value:" + value);
            session.setAttribute(String.valueOf(key), value);
        }
    }

    public static Object getSessionAttributeValue(String code, HttpSession session) {
        return session.getAttribute(code);
    }

    @SuppressWarnings("unused")
    private Object getDataMapValue(String code) {
        return dataMap.get(code);
    }

    /**
     * 
     * 根据系统配置初始化信息
     *
     * @author  严华
     * @param param [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     */
    @SuppressWarnings("unused")
    private void initSessionByCfg(Map<String, Object> param) {

    }

    /**
     * 
     * <功能简述>
     *
     * @author  严华
     * @param staffId
     * @param roleId [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     */
    private void initPrivilegeInfo(String staffId, String roleId) {
        // 按需要补充
    }

    /**
     * 
     * 初始化当前登录角色菜单权限信息
     *
     * @author  严华
     * @param userId
     * @param roleIds [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     */
    private void initMenuInfoList(String userId, String roleIds) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("role_ids", roleIds);
        param.put("staff_id", userId);
        List<Map<String, String>> menuInfoList = baseService.findList(SQL_PREFIX + "selectMenuInfoList", param);
        dataMap.put(Constant.SESSION_MENU_INFO_LIST, ObjectUtil.defaultIfNull(menuInfoList, SPACE));
    }

    /**
     * 
     * 初始化角色信息
     *
     * @author  严华
     * @param userId
     * @return [参数说明]
     * 
     * @return String [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     */
    private String initStaffRole(String userId) {
        String roleIds = "";
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("user_id", userId);
        List<Map<String, String>> dataList = baseService.findList(SQL_PREFIX + "selectStaffRoleList", param);

        for (Map<String, String> item : dataList) {
            if (StringUtil.isValid(roleIds)) {
                roleIds += "," + String.valueOf(item.get("ROLE_ID"));
            } else {
                roleIds = String.valueOf(item.get("ROLE_ID"));
            }
        }

        dataMap.put(Constant.SESSION_ROLE_IDS, ObjectUtil.defaultIfNull(roleIds, SPACE));

        dataMap.put(Constant.SESSION_ROLE_LIST, ObjectUtil.defaultIfNull(dataList, SPACE));

        return roleIds;
    }

    /**
     * 
     * 将员工信息添加到缓存中
     *
     * @author  严华
     * @param userId [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     */
    private void initStaffInfo(String userId) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("user_id", userId);
        Map<String, String> userInfoMap = this.baseService.selectOne(SQL_PREFIX + "selectStaffInfoList", param);

        dataMap.put(Constant.SESSION_USER_ID, userId);
        dataMap.put(Constant.SESSION_User_NAME, ObjectUtil.defaultIfNull(userInfoMap.get("USER_NAME"), SPACE));
        dataMap.put(Constant.SESSION_LOGIN_CODE, ObjectUtil.defaultIfNull(userInfoMap.get("LOGIN_CODE"), SPACE));
        dataMap.put(Constant.SESSION_LAST_LOGIN_DATE, ObjectUtil.defaultIfNull(userInfoMap.get("LAST_LOGIN_DATE"), SPACE));

        // 存userId到cookie
        CookieUtil cookie = new CookieUtil(ServletActionContext.getRequest(), ServletActionContext.getResponse());
        cookie.addCookie("USER_ID", userId);
    }

    /**
     * 
     * 初始化baseService
     *
     * @author  严华
     * @param request [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     */
    private void initBaseService(HttpServletRequest request) {
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
        baseService = (BaseService) wac.getBean("baseService");
    }
}
